package com.mathpractise.service.impl;

import com.mathpractise.dto.QuestionDTO;
import com.mathpractise.dto.request.AnswerQuestionRequestDTO;
import com.mathpractise.dto.request.StartTrainingRequestDTO;
import com.mathpractise.dto.response.AnswerQuestionResponseDTO;
import com.mathpractise.dto.response.FinishTrainingResponseDTO;
import com.mathpractise.dto.response.StartTrainingResponseDTO;
import com.mathpractise.dto.response.StatisticsReportDTO;
import com.mathpractise.model.AnswerDetail;
import com.mathpractise.model.Question;
import com.mathpractise.model.TrainingSession;
import com.mathpractise.question.generator.QuestionGenerator;
import com.mathpractise.question.generator.QuestionGeneratorConfig;
import com.mathpractise.repository.TrainingRepository;
import com.mathpractise.service.StatisticsService;
import com.mathpractise.service.TrainingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * 训练服务实现类
 */
@Service
public class TrainingServiceImpl implements TrainingService {
    
    private static final Logger logger = LoggerFactory.getLogger(TrainingServiceImpl.class);
    
    @Autowired
    private TrainingRepository trainingRepository;
    
    @Autowired
    private StatisticsService statisticsService;
    
    @Autowired
    private QuestionGeneratorConfig questionGeneratorConfig;
    
    @Override
    public StartTrainingResponseDTO startTraining(StartTrainingRequestDTO request) {
        logger.info("开始训练服务: moduleType={}, questionType={}", 
            request.getModuleType(), request.getTrainingConfig().getQuestionType());
        
        // 创建训练会话
        String sessionId = UUID.randomUUID().toString();
        TrainingSession session = new TrainingSession(sessionId, request.getModuleType(), request.getTrainingConfig());
        
        // 获取题目生成器
        QuestionGenerator questionGenerator = questionGeneratorConfig.getGenerator(request.getTrainingConfig().getQuestionType());
        
        if (questionGenerator == null) {
            logger.error("未找到对应的题目生成器: {}", request.getTrainingConfig().getQuestionType());
            throw new RuntimeException("Unsupported question type: " + request.getTrainingConfig().getQuestionType());
        }
        
        // 生成题目
        List<Question> questions = questionGenerator.generateQuestions(request.getTrainingConfig());
        logger.info("生成 {} 道题目", questions.size());
        
        // 为题目设置ID
        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            question.setId("Q" + i); // 添加题目ID
        }
        
        session.setQuestions(questions);
        
        // 保存会话
        trainingRepository.save(session);
        logger.info("训练会话保存成功: sessionId={}", sessionId);
        
        // 构造响应
        StartTrainingResponseDTO response = new StartTrainingResponseDTO();
        response.setSessionId(sessionId);
        // 设置第一题
        if (!questions.isEmpty()) {
            response.setFirstQuestion(convertToQuestionDTO(questions.get(0), 0, questions.size()));
        }
        
        logger.info("训练开始完成: sessionId={}", sessionId);
        return response;
    }
    
    @Override
    public AnswerQuestionResponseDTO answerQuestion(AnswerQuestionRequestDTO request) {
        logger.info("处理答题请求: sessionId={}, questionId={}", request.getSessionId(), request.getQuestionId());
        
        // 获取训练会话
        Optional<TrainingSession> optionalSession = trainingRepository.findById(request.getSessionId());
        if (!optionalSession.isPresent()) {
            logger.error("找不到训练会话: sessionId={}", request.getSessionId());
            throw new RuntimeException("训练会话不存在: " + request.getSessionId());
        }
        TrainingSession session = optionalSession.get();
        
        // 查找当前题目
        List<Question> questions = session.getQuestions();
        Question currentQuestion = null;
        int questionIndex = -1;
        for (int i = 0; i < questions.size(); i++) {
            if (questions.get(i).getId().equals(request.getQuestionId())) {
                currentQuestion = questions.get(i);
                questionIndex = i;
                break;
            }
        }
        
        if (currentQuestion == null) {
            logger.error("找不到题目: questionId={}", request.getQuestionId());
            throw new RuntimeException("题目不存在: " + request.getQuestionId());
        }
        
        // 检查答案
        boolean isCorrect = Objects.equals(request.getUserAnswer(), currentQuestion.getCorrectAnswer());
        
        // 记录答题详情
        AnswerDetail answerDetail = new AnswerDetail();
        answerDetail.setQuestionId(currentQuestion.getId());
        try {
            Integer userAnswerInt = Integer.valueOf(request.getUserAnswer());
            answerDetail.setUserAnswer(userAnswerInt);
        } catch (NumberFormatException e) {
            logger.warn("用户答案无法转换为整数: {}", request.getUserAnswer());
            answerDetail.setUserAnswer(null); // 或者根据业务需求设置默认值
        }
        answerDetail.setCorrect(isCorrect);
        answerDetail.setAnswerTime(new java.util.Date());
        // 注意：当前实现中没有计算用时，所以暂时不设置timeSpent
        
        // 添加答题详情到会话
        if (session.getAnswerDetails() == null) {
            session.setAnswerDetails(new ArrayList<>());
        }
        session.getAnswerDetails().add(answerDetail);
        
        // 更新会话
        trainingRepository.update(session);
        logger.info("答题详情记录成功: sessionId={}, questionId={}, isCorrect={}", 
            request.getSessionId(), request.getQuestionId(), isCorrect);
        
        // 构造响应
        AnswerQuestionResponseDTO response = new AnswerQuestionResponseDTO();
        // 设置下一题
        if (questionIndex + 1 < questions.size()) {
            response.setNextQuestion(convertToQuestionDTO(questions.get(questionIndex + 1), questionIndex + 1, questions.size()));
            response.setLastQuestion(false);
        } else {
            response.setNextQuestion(null); // 没有下一题了
            response.setLastQuestion(true);
        }
        
        logger.info("答题处理完成: sessionId={}, questionId={}", request.getSessionId(), request.getQuestionId());
        return response;
    }
    
    @Override
    public FinishTrainingResponseDTO finishTraining(String sessionId) {
        logger.info("结束训练: sessionId={}", sessionId);
        
        // 获取训练会话
        Optional<TrainingSession> optionalSession = trainingRepository.findById(sessionId);
        if (!optionalSession.isPresent()) {
            logger.error("找不到训练会话: sessionId={}", sessionId);
            throw new RuntimeException("训练会话不存在: " + sessionId);
        }
        TrainingSession session = optionalSession.get();
        
        // 标记训练结束
        session.setEndTime(new java.util.Date());
        trainingRepository.update(session);
        logger.info("训练会话标记为已完成: sessionId={}", sessionId);
        
        // 生成统计报告
        StatisticsReportDTO report = statisticsService.generateStatisticsReport(sessionId);
        FinishTrainingResponseDTO response = new FinishTrainingResponseDTO();
        response.setSessionId(sessionId);
        response.setStatisticsReport(report);
        logger.info("统计报告生成完成: sessionId={}", sessionId);
        
        return response;
    }
    
    @Override
    public List<TrainingSession> getAllSessions() {
        return trainingRepository.findAll();
    }
    
    /**
     * 将 Question 对象转换为 QuestionDTO
     */
    private QuestionDTO convertToQuestionDTO(Question question, int currentIndex, int totalQuestions) {
        QuestionDTO dto = new QuestionDTO();
        dto.setId(question.getId());
        dto.setExpression(question.getExpression());
        dto.setOptions(question.getOptionStringList());
        dto.setQuestionIndex(currentIndex);
        dto.setTotalQuestions(totalQuestions);
        return dto;
    }
}